package rs.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import rs.util.CanonicalString;
import rs.util.TuningParameters;

/* Classe responsabile del parsing di un JSON relativo ai tag di un brano */
public class TagsParser {

	public List<String> parse(String response) {		
		List<String> tag_list = new ArrayList<String>();
		if (!response.substring(2,7).equals("error")) {
			try {					
				JSONObject json = (JSONObject) new JSONParser().parse(response);
				JSONObject tags = (JSONObject) json.get("toptags");

				try {				
					JSONArray tag_array = (JSONArray) tags.get("tag");	

					if (tag_array == null) {
						return tag_list;
					}

					for (int i = 0; i < tag_array.size() && i < TuningParameters.TAG_TRACK_LIMIT; i++) {
						tag_list.add(this.getTag(tag_array.get(i)));
					}
				}
				catch (ClassCastException cce) {
					tag_list.add(this.getTag(tags.get("tag")));
				}

			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return tag_list;
	}

	private String getTag(Object obj) {
		JSONObject json_obj = (JSONObject) obj;
		String tag_name = (String) json_obj.get("name");
		return new CanonicalString(tag_name).toString();
	}

}
